package cz.possoft.client.threads;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import cz.possoft.client.utils.SaveLoadUtils;
import cz.possoft.generic.utils.GenericUtils;

/**
  *  
  * Tato trida slouzi k pripojovani na http server a k poslani pozadavku na tento server.
  * Pozadavek musi byt poslan, aby byl na vzdalenem serveru spusten program PossoftNetServer
  * ktery je spusten pres cgi skript
  * 
  * @author mara
  */
public class HttpRequestThread extends Thread {
	
	private ConnectThread connectThread;
	
	private boolean httpSuccessFlag;
	
    HttpRequestThread(ConnectThread connectThread) {
    	this.connectThread = connectThread;
    	httpSuccessFlag = false;
    	start();
    }
    
    public void run() {
    	try {
    		// nejdriv cekame nekolik sekund nez posleme http request. Zaroven s timto vlaknem totiz bezi connectThread
    	    //sleep(3000);
    	    // pokud uz se spojeni v connectThread povedlo, pak http request neposilame
    	    if (!connectThread.getConnectFlag()) {
    	    	//System.out.println("HttpRequestThread: bod pred poslanim requestu.");
    	        httpSuccessFlag = sendingHttpRequestToFi(GenericUtils.CGI_SCRIPT_TO_HTTP_REQUEST_ADDRESS);
    	        // probuzeni connectThreadu po zaslani http requestu.
    	        synchronized(connectThread) {
    	            connectThread.notify();
    	        }    	
    	    }
    	}
    	catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    // metoda je urcena k poslani http requestu na vzdaleny server, cimz by se mel na tomto serveru spustit pres
    // cgi skript PossoftNetServer    
    private boolean sendingHttpRequestToFi(String cgiParam) {
    	boolean httpSuccessFlag = false;
        try {                                
            Socket httpSocket = new Socket(SaveLoadUtils.returnHostName(), 80);
            PrintWriter httpWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(httpSocket.getOutputStream())), true);
            httpWriter.println("GET " + cgiParam + " HTTP/1.0\n\n");
            httpWriter.close();
            httpSocket.close();
            httpSuccessFlag = true;
        } catch (Exception eee) {
            eee.printStackTrace();                                    
        }    	
        return httpSuccessFlag;
    }    
	

}
